<template>
  <div class="ad_babox">
    <!-- 搜索 -->
    <div class="seach">
      <el-input placeholder="请输入广告标题" v-model="listQuery.name" clearable></el-input>
      <el-input placeholder="请输入广告内容" v-model="listQuery.content" clearable></el-input>
      <el-button type="primary" icon="el-icon-search" @click="seach">查找</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="add">添加</el-button>
      <el-button :loading="downloadLoading" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>
    <!-- 列表 --> 
    <div class="list">
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="广告ID" sortable align="center"> </el-table-column>
        <el-table-column prop="name" label="广告标题" align="center"> </el-table-column>
        <el-table-column prop="content" label="广告内容" align="center"></el-table-column>
        <el-table-column prop="url" label="广告图片" align="center">
          <template slot-scope="scope">
            <el-image :src="scope.row.url" :preview-src-list="[scope.row.url]"></el-image>


          </template>
        </el-table-column>
        <el-table-column prop="position" label="广告位置" align="center"> </el-table-column>
        <el-table-column prop="link" label="活动链接" align="center"></el-table-column>
        <el-table-column prop="enabled" label="是否启用" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.enabled == false ? 'primary' : 'success'" disable-transitions>{{
              scope.row.enabled == true ? '启用' : '不启用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deletee(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
    <!-- 弹窗 -->
    <div>
      <el-dialog :title="tit" :visible.sync="dialogFormVisible">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
          <el-form-item label="广告标题" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="广告内容" prop="content">
            <el-input v-model="ruleForm.content"></el-input>
          </el-form-item>

          <el-form-item label="广告图片" prop="url">





            <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadPicUrl"
              class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
              <img v-if="ruleForm.url" :src="ruleForm.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>



          </el-form-item>

          <el-form-item label="广告位置" prop="position">
            <el-select v-model="ruleForm.position" placeholder="请选择活动区域">
              <el-option label="首页" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动链接" prop="link">
            <el-input v-model="ruleForm.link"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" prop="enabled">
            <el-select v-model="ruleForm.enabled" placeholder="请选择活动区域">
              <el-option label="启用" value="true"></el-option>
              <el-option label="不启用" value="false"></el-option>
            </el-select>
          </el-form-item>


        </el-form>



        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { listAd, deleteAd, createAd, updateAd } from '@/api/ad'
import { downloadXlsx } from '../../utils/xlsx';
import { createStorage, uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'Ad',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      // 导出
      downloadLoading: false,
      // 搜索
      input1: '',
      input2: '',

      // 列表
      tableData: [],

      // 分页
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'add_time',
        order: 'desc',
        name: '',
        content: ''

      },

      // 弹窗

      tit: '',
      dialogFormVisible: false,
      ruleForm: {
        content: "",
        enabled: true,
        link: "",
        name: "",
        position: 1,
        url: '',
      },
      rules: {
        name: [
          { required: true, message: '广告标题', trigger: 'blur' },

        ],
        content: [
          { required: true, message: '广告内容', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '广告内容', trigger: 'blur' }
        ]
      },

      arr: null,
      // 
      realyurl: '',



    }
  },
  created() {
    this.getList()
  },
  methods: {

    async getList() {
      let res = await listAd(this.listQuery)
      if (res) {
        // console.log(res.data.data);
        this.tableData = res.data.data.list
        this.total = res.data.data.total
      }
    },
    // 查找
    seach() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.getList()
    },


    // 删除
    async deletee(row) {
      let res = await deleteAd(row)
      if (res) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success'
        });
        this.getList()
      }
    },

    // 添加
    add() {
      this.tit = '创建'
      this.dialogFormVisible = true
      this.ruleForm = {
        content: "",
        enabled: '启用',
        link: "",
        name: "",
        position: '首页',
        url: '',
      }
    },


    // 编辑
    edit(row) {
      this.tit = '编辑'
      this.dialogFormVisible = true
      // console.log(row);
      this.ruleForm = {
        content: row.content,
        enabled: row.enabled == true ? '启用' : '不启用',
        link: row.link,
        name: row.name,
        position: '首页',
        url: row.url,
      }

      let arr = {
        addTime: row.addTime,
        content: row.content,
        deleted: row.deleted,
        enabled: row.enabled,
        id: row.id,
        link: row.link,
        name: row.name,
        position: row.position,
        updateTime: row.updateTime,
        url: row.url,
      }
      this.arr = arr
    },

    // 确定
    submitForm(formName) {

      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // this.ruleForm.url=this.realyurl
          if (this.ruleForm.enabled == '启用') {
            this.ruleForm.enabled = true
          }

          this.ruleForm.position = 1
          if (this.tit == '创建') {

            let res = await createAd(this.ruleForm)


            if (res) {

              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success'
              });
            }
          } else if (this.tit == '编辑') {


            let preview = []
            preview.push(this.ruleForm.url)
            let arr = {
              addTime: this.arr.addTime,
              content: this.ruleForm.content,
              deleted: this.arr.deleted,
              enabled: this.ruleForm.enabled = false ? 'true' : 'false',
              id: this.arr.id,
              link: this.ruleForm.link,
              name: this.ruleForm.name,
              position: this.ruleForm.position,
              updateTime: this.arr.updateTime,
              url: this.ruleForm.url,

            }




            let res = await updateAd(arr)
            if (res) {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success'
              });
            }
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 关闭
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields();
    },
    oonchange(file, fileList) {
      console.log(file, fileList);
    },
    // 文件上传成功时的钩子
    handleAvatarSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      this.ruleForm.url = URL.createObjectURL(file.raw);
      // console.log(res,'res');
      // console.log(file.name, 'file');
      // this.realyurl='http://admin.bsmall.byesame.com/'+file.name
      // console.log(this.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    // 图片处理
    uploadPicUrl: function (response) {
      // console.log(response, '上传图片');

      this.ruleForm.url = response.data.url
    },
    // 导出
    handleDownload() {
      let datList = [];
      this.tableData.forEach((item) => {
        let arr = []
        arr[0] = item.id;
        arr[1] = item.name;
        arr[2] = item.content;
        arr[3] = item.url;
        arr[4] = item.position;
        arr[5] = item.link;
        arr[6] = item.enabled == true ? '启用' : '不启用';
        datList.push(arr)
      })
      // console.log(datList);
      datList.unshift(['广告ID', '广告标题', '广告内容', '广告图片', '广告位置', '活动链接', '是否启用'])
      downloadXlsx(datList, "广告管理.xlsx")


    },
  },

  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },





}
</script>
<style scoped lang="scss">
.ad_babox ::v-deep {
  margin: 20px;

  .seach {
    .el-input {
      width: 200px;
    }
  }

  .list {
    margin-top: 20px;

    img {
      width: 80px;
      height: 40px;
    }
  }

  .demo-ruleForm {
    width: 60%;
  }


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>